'use strict'
let { Products, Op } = require('../model');

//显示列表和查询
let fn_List = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || 0;
    let list;
    if (keyword) {
        list = await Products.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { title: keyword },
                    { abstract: keyword },
                    { content: keyword },
                    { classify: keyword },
                    { author: keyword },
                    { time: keyword },
                ]
            },
            order: ['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '查询成功',
        }
    } else {
        list = await Products.findAll({
            order: ['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求数据成功'
        }
    }
}

//获取ID
let fn_getId = async (ctx, next) => {
    let id = ctx.request.params.id;
    let list = await Products.findByPk(id);
    if (list) {
        ctx.body = {
            code: 1000,
            data: list,
            msg: '查询ID成功'
        }
    } else {
        ctx.body = {
            code: 404,
            data: null,
            msg: '查询ID失败'
        }
    }
}

//添加
let fn_Add = async (ctx, next) => {
    let obj = ctx.request.body;
    await Products.create(obj);
    ctx.body = {
        code: 1000,
        data: obj,
        msg: '添加成功'
    }
}

//编辑
let fn_Update = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let list = await Products.findByPk(id);
    if (list) {
        Products.update(obj, {
            where: { id: id }
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '编辑成功'
        }
    }else{
        ctx.body = {
            code: 404,
            data: null,
            msg: '失败成功'
        }
    }
}

//删除
let fn_Delete = async(ctx,next)=>{
    let id = ctx.request.params.id;
    let list = await Products.findByPk(id);
    if(list){
        Products.destroy({
            where:{id:id}
        })
        ctx.body={
            code:1000,
            data:{id},
            msg:'删除成功'
        }
    }else{
         ctx.body={
            code:404,
            data:null,
            msg:'删除失败'
         }
    }
}

module.exports = {
    'get /product': fn_List,
    'get /product/:id': fn_getId,
    'post /product':fn_Add,
    'put /product/:id':fn_Update,
    'delete /product/:id':fn_Delete,
}